package com.hluck.localbluetooth.ui.activity

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.databinding.DataBindingUtil
import com.hluck.localbluetooth.R
import com.hluck.localbluetooth.app.util.BluetoothController
import com.hluck.localbluetooth.databinding.ActivityMainBinding
import java.lang.ref.WeakReference

fun String.toast(context: Context) {
    Toast.makeText(context, this, Toast.LENGTH_SHORT).show()
}

class MainActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivityMainBinding
    private lateinit var mBluetoothController:BluetoothController

    private val bluetoothReceiver = object :BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            when(intent?.action){
                BluetoothAdapter.ACTION_STATE_CHANGED -> {
                    val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
                    when(state){
                        BluetoothAdapter.STATE_OFF -> "蓝牙已关闭".toast(this@MainActivity)
                        BluetoothAdapter.STATE_ON -> "蓝牙已打开".toast(this@MainActivity)
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        mBluetoothController = BluetoothController()
        val  intentfilter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(bluetoothReceiver,intentfilter)

        initView()
    }

    private fun initView(){
        mBinding.apply {
            btnSupport.setOnClickListener {
                val isSupport = mBluetoothController.isSupported()
                "当前设备是否支持蓝牙：$isSupport".toast(this@MainActivity)
            }

            btnState.setOnClickListener {
                val state = mBluetoothController.getBluetoothState()
                "当前蓝牙是否打开：$state".toast(this@MainActivity)
            }

            btnOn.setOnClickListener {
                mBluetoothController.turnOnBluetooth(WeakReference(this@MainActivity), 1)
            }

            btnOff.setOnClickListener {
                mBluetoothController.offBluetooth()
            }

        }

    }

    override fun onStop() {
        unregisterReceiver(bluetoothReceiver)
        super.onStop()
    }
}